<script setup lang="ts">
import type { TableProps } from 'ant-design-vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode, ref } from 'vue'
import { cloneDeep } from 'lodash'
import SalesItemAdd from './components/sales-item-add.vue'
import type { SalesDetailItem, SalesDetailModel } from '@/api/sales/sales-list.ts'
import { getSalesDetailInfo } from '@/api/sales/sales-list.ts'
import dayjs from 'dayjs'

const formData = ref<SalesDetailModel>()

const visible = ref(false)

const salesItemAdd = ref<InstanceType<typeof SalesItemAdd>>()

async function handleAdd() {
  console.log('当前打开时使用的销售单号是：关联采购订单ID:', formData.value?.purchaseId)
  const purchaseItem = ref<SalesDetailItem>(<SalesDetailItem>{
    customerId: 0,
    productId: 0,
    salesId: formData.value?.salesId,
    sdiActualAmount: 0,
    sdiCostUnitPrice: 0,
    sdiFullCostPrice: 0,
    sdiId: 0,
    sdiPrice: 0,
    sdiPureProfit: 0,
    sdiQuantity: 0,
    totalPrice: 0,
  })
  console.log(purchaseItem)
  salesItemAdd.value?.open(purchaseItem.value,<number>formData.value?.purchaseId)
}

async function handleEdit(record: SalesDetailItem) {
  salesItemAdd.value?.open(record,<number>formData.value?.purchaseId)
}

function open(record?: SalesDetailModel) {
  console.log(`进入open方法，当前销售单是：${record?.salesId}`)
  visible.value = true
  formData.value = cloneDeep(record)
  getItemsList()
}

const dataSource = ref<SalesDetailItem[]>([])

const pagination = ref({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40', '50'],
  showQuickJumper: true,
  total: 0,
})

// 获取销售单信息详情
async function getItemsList() {
  console.log(formData.value)
  console.log(formData.value?.salesId)
  const reqForm = ref<SalesDetailModel>({
    salesId: formData.value?.salesId,
  })
  const { data } = await getSalesDetailInfo(reqForm.value)
  formData.value = data
  dataSource.value = data?.items ?? []
  pagination.value.total = data?.items.length ?? 0
  console.log(dataSource.value)
}

/*
  处理删除对话框
*/
function showConfirm(index: SalesDetailItem) {
  Modal.confirm({
    title: '删除任务',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { }, '确定要删除该任务吗?'),
    cancelText: '取消',
    okText: '确认',
    onOk() {
      dataSource.value.splice(index.sdiId, 1)
    },
    class: 'test',
  })
}

function onCreateTimeChange(value: any) {
  return dayjs(value * 1000).format('YYYY-MM-DD')
}

/*onMounted(() => {
  getItemsList()
})*/

function onClose() {
  visible.value = false
  console.log('关闭，准备刷新列表')
}

function onAfterOpenChange() {
  // console.log('加载动画结束')
}

function purchaseDetailItemSave() {
  // 刷新子级列表
}

const loading = shallowRef(false)

const columns = shallowRef([
  {
    title: '销售明细编号',
    dataIndex: 'sdiId',
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
  },
  {
    title: '数量，斤数',
    dataIndex: 'sdiQuantity',
  },
  {
    title: '销售单价',
    dataIndex: 'sdiPrice',
  },
  {
    title: '销售自动总价',
    dataIndex: 'totalPrice',
  },
  {
    title: '关联客户名称',
    dataIndex: 'customerName',
  },
  {
    title: '销售实际总价',
    dataIndex: 'sdiActualAmount',
  },
  {
    title: '成本单价',
    dataIndex: 'sdiCostUnitPrice',
  },
  {
    title: '成本总价',
    dataIndex: 'sdiFullCostPrice',
  },
  {
    title: '纯利润',
    dataIndex: 'sdiPureProfit',
  },
  {
    title: '销售日期',
    dataIndex: 'sdiDate',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
  },
])

const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

const tableSize = ref<string[]>(['large'])

defineExpose({
  open,
})
</script>

<template>
  <a-drawer v-model:open="visible" width="1200px" title="销售单详情" @close="onClose" @afterOpenChange="onAfterOpenChange">
    <!-- 头部 -->
    <a-card>
      <a-row :gutter="16">
        <a-descriptions title="销售单信息">
          <a-descriptions-item label="销售单号">
            {{ formData?.purchaseId }}
          </a-descriptions-item>
          <a-descriptions-item label="自动总金额">
            {{ formData?.salesTotalPrice }}
          </a-descriptions-item>
          <a-descriptions-item label="实际销售总金额">
            ￥ {{ formData?.salesActualTotalPrice }}
          </a-descriptions-item>
          <a-descriptions-item label="总计销售纯利润">
            ￥ {{ formData?.salesPureProfit }}
          </a-descriptions-item>
          <a-descriptions-item label="备注">
            {{ formData?.salesRemarks }}
          </a-descriptions-item>
          <a-descriptions-item label="销售人">
            {{ formData?.salesPerson }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ onCreateTimeChange(formData?.salesCreateTime) }}
          </a-descriptions-item>
        </a-descriptions>
      </a-row>
    </a-card>

    <!-- 列表 -->
    <a-card class="mt-5">
      <template #title>
        <!-- 底部添加按钮 -->
        <a-button type="dashed" @click="handleAdd()">
          + 添加新销售明细
        </a-button>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-error @click="showConfirm(scope?.record as SalesDetailItem)">
                作废
              </a>
              <a @click="handleEdit(scope?.record as SalesDetailItem)">
                编辑
              </a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>



    <!-- 销售明细添加 -->
    <SalesItemAdd ref="salesItemAdd" @purchaseDetailItemSave="purchaseDetailItemSave"></SalesItemAdd>
  </a-drawer>
</template>

<style>
.a-extra {
  display: flex;
  align-items: center;
  justify-content: end;
}
</style>
